package com.fablesoft.projectdatacollect.ui;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.bean.AppInfoBean;
import com.fablesoft.projectdatacollect.bean.AppInfoResponse;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.bean.LoginResponse;
import com.fablesoft.projectdatacollect.bean.Setting;
import com.fablesoft.projectdatacollect.dao.SettingDao;
import com.fablesoft.projectdatacollect.http.HttpListener;
import com.fablesoft.projectdatacollect.http.HttpThread;
import com.fablesoft.projectdatacollect.http.RequestData;
import com.fablesoft.projectdatacollect.services.VersionUpdateService;
import com.fablesoft.projectdatacollect.util.CommonUtils;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.util.JyCustomDialog;
import com.fablesoft.projectdatacollect.util.PreferencesUtil;

import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends BaseRequestActivity implements TextView.OnEditorActionListener, View.OnClickListener {

    private EditText loginNameEt;
    private EditText passwordEt;
    private TextView loginBtn;
    private TextView tvName;
    private TextView tvSystemName;
    private TextView tvVersion;

    private String loginName;
    private String password;
    private static final int LOGIN_CODE = 200;//登录
    private static final int GET_APPINFO_CODE = 100;
    private boolean loginTimeOut;
    private long[] mClocks = new long[5];
    private Setting setting;
    private SettingDao settingDao;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_new);

        init();
        initUrl();

        loginTimeOut = getIntent().getBooleanExtra("loginTimeOut", false);
        if (loginTimeOut) {
            createPromptDialog(this, null, getResources().getString(R.string.login_time_out), getResources().getString(R.string.ok), null);
        }
    }

    private void init() {
        loginBtn = (TextView) findViewById(R.id.login_btn);
        loginNameEt = (EditText) findViewById(R.id.username_text);
        passwordEt = (EditText) findViewById(R.id.password_text);
        tvName = (TextView) findViewById(R.id.tv_setting_name);
        tvSystemName = (TextView) findViewById(R.id.tv_system_name);
        tvVersion = (TextView) findViewById(R.id.tv_version);
        tvVersion.setText("V" + MyApplication.getInstance().getLocalVersion());
        loginBtn.setOnClickListener(this);
        tvSystemName.setOnClickListener(this);
        SharedPreferences mSharedPreferences = PreferencesUtil
                .getSharedPreferences(null);
        loginName = mSharedPreferences.getString("loginName", "");
        password = mSharedPreferences.getString("password", "");
        loginNameEt.setText(loginName);
        passwordEt.setText(password);
        passwordEt.setOnEditorActionListener(this);
    }

    private void startUpdateService() {
        if (MyApplication.getInstance().isCheckUpdate()) {
            MyApplication.getInstance().setCheckUpdate(false);
            startService(new Intent(LoginActivity.this, VersionUpdateService.class));
        }
    }

    private void login() {
        loginName = loginNameEt.getText().toString().trim();
        password = passwordEt.getText().toString().trim();
        if (TextUtils.isEmpty(loginName)) {
            Toast.makeText(LoginActivity.this, R.string.username_empty_hint,
                    Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(LoginActivity.this, R.string.password_empty_hint,
                    Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userName", loginName);
        params.put("password", password);
        createLoadingDialog(LoginActivity.this);
        MyApplication.getInstance().setSessionId("");
        showDialog("登录中");
        HttpThread httpThread = new HttpThread(Config.LOGIN_URL,
                new HttpListener() {
                    @Override
                    public void onRequestFinish(BaseResponse response) {
                        Message msg = mHandler.obtainMessage();
                        msg.obj = response;
                        msg.what = LOGIN_CODE;
                        mHandler.sendMessage(msg);
                    }

                    @Override
                    public void onNotLogin(BaseResponse response) {
                    }
                }, params, LoginResponse.class);
        MyApplication.getInstance().getRequestQueue().execute(httpThread);
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case LOGIN_CODE:
                    dismissDialog();
                    LoginResponse result = (LoginResponse) msg.obj;
                    if (result == null) {
                        Toast.makeText(LoginActivity.this, "请检查网络或服务器请求路径",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        if (result.getSuccess()) {
                            Toast.makeText(LoginActivity.this, "登录成功",
                                    Toast.LENGTH_SHORT).show();
                            Editor editor = PreferencesUtil.getSharedPreferencesEditor(null);
                            // 保存到本地
                            editor.putString("loginName", loginName);
                            editor.putString("password", password);
                            editor.commit();
                            MyApplication.getInstance().saveUserInfo(result);
                            if (!loginTimeOut) {
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                            }
                            finish();
                        } else {
                            if (TextUtils.isEmpty(result.getMessage())) {
                                Toast.makeText(LoginActivity.this, "登录失败",
                                        Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(LoginActivity.this, result.getMessage(),
                                        Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    break;

                case GET_APPINFO_CODE:
                    AppInfoResponse response = (AppInfoResponse) msg.obj;
                    if (response == null) {
                        Toast.makeText(LoginActivity.this, "请检查网络或服务器请求路径", Toast.LENGTH_LONG).show();
                        tvName.setText("");
                        setting.setProjectName("");
                    } else {
                        AppInfoBean appInfo = response.getAppInfo();
                        tvName.setText(appInfo.getValue());
                        setting.setProjectName(appInfo.getValue());
                    }
                    settingDao.insertSetting(setting);
                    break;
            }
        }

        ;
    };

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_GO) {
            CommonUtils.hideSoftKeyboard(this);
            login();
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.login_btn:
                login();
                break;
            case R.id.tv_system_name:
                displaySetting();
                break;
            default:
                break;
        }
    }

    private void displaySetting() {
        System.arraycopy(mClocks, 1, mClocks, 0, mClocks.length - 1);
        mClocks[mClocks.length - 1] = SystemClock.uptimeMillis();
        if (SystemClock.uptimeMillis() - mClocks[0] <= 1000) {
            showSettingDialog();
            mClocks = new long[5];
        }
    }

    private void showSettingDialog() {
        final JyCustomDialog dialog = new JyCustomDialog(this).createTwoButtonWithEditTextDialog();
        dialog.setMessage("地址：").setEditText(Config.BASE_WITH_DOMAIN)
                .setLeftBtnClick(R.string.bt_cancel, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.cancelAndHideKey();
                    }
                }).setRightBtnClick(R.string.bt_confirm, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveUrl(handleUrl(dialog.getInputMsg()));
                getAppInfo();
                startUpdateService();
                dialog.cancelAndHideKey();
            }
        }).show();
    }

    private String handleUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            Log.d("sglei-setting", "url is null");
            return null;
        }
        url = url.trim();
        if (!url.contains("http")) {
            url = "http://" + url;
        }
        Config.initUrl(url);
        Log.d("sglei-setting", "Config.BASE_WITH_DOMAIN = " + Config.BASE_WITH_DOMAIN);
        return url;
    }

    private void saveUrl(String url) {
        if (TextUtils.isEmpty(url)) {
            return;
        }
        // 将url配置存入本地数据库
        setting.setId(CommonUtils.SETTING_URL_ID);
        setting.setServerUrl(url);
        settingDao.insertSetting(setting);
    }

    private void initUrl() {
        if (settingDao == null) {
            settingDao = new SettingDao(this);
        }
        setting = settingDao.getCurrentInfo();
        if (setting == null) {
            setting = new Setting();
        }
        handleUrl(setting.getServerUrl());
        tvName.setText(setting.getProjectName());
        if (TextUtils.isEmpty(Config.BASE_WITH_DOMAIN)) {
            Toast.makeText(LoginActivity.this, "请设置服务器地址", Toast.LENGTH_SHORT);
            return;
        }
        startUpdateService();
    }

    private void getAppInfo() {
        Map<String, Object> params = new HashMap<>();
        params.put("page", 1);
        params.put("size", 1);
        Map<String, Object> mapParams = new HashMap<>();
        mapParams.put("key", "project_name");
        params.put("mapParams", mapParams);
        new RequestData(Config.APP_INFO_URL, params, AppInfoResponse.class, new HttpListener() {
            @Override
            public void onRequestFinish(BaseResponse response) {
                Message msg = mHandler.obtainMessage();
                msg.obj = response;
                msg.what = GET_APPINFO_CODE;
                mHandler.sendMessage(msg);
            }

            @Override
            public void onNotLogin(BaseResponse response) {
            }
        }).sendJsonPost();
    }
}
